#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "defs.h"

#define NUM_THREADS 10 // 线程数量

typedef struct // 创建一个结构体来传递线程所需的参数:行和列的起始和结束索引
{
    int startRow, endRow;
    int n;
    double *a,*b,*c;
} ThreadArg;

void *multiplyMatrices(void *arg) // 结构体指针变量作形参
{
    ThreadArg *threadArgs = (ThreadArg *)arg;
    int s=threadArgs->n;
    //printf("s=%d\n",s);
    int i, j, q;
    for (i = threadArgs->startRow; i < threadArgs->endRow; i++)
    {
        for (j = 0; j < s; j++)
        {
            //printf("i=%d,j=%d,s=%d\n",i,j,s);
            threadArgs->c[i * s + j] = 0;
            for (q = 0; q < s; q++)
            {
                threadArgs->c[i * s + j] += threadArgs->a[i * s + q] * threadArgs->b[q * s + j];
            }
        }
    }
    return NULL;
}

void MY_MMult(int m,int n,int k,double *a,int lda,double *b,int ldb,double *c,int ldc)
{
    pthread_t threads[NUM_THREADS];    // 线程tid
    ThreadArg threadArgs[NUM_THREADS]; // 结构体数组（10组数据：起始列，结束列，还有数组AB的地址）
    int i;
     
    //threadArgs->a=a;
    //threadArgs->b=b;
    //threadArgs->c=c;
    
    // 创建线程
    int rowsPerThread = n / NUM_THREADS; // 计算每个线程算多少列
    for (i = 0; i < NUM_THREADS; i++)
    {
        threadArgs[i].n=n;
        threadArgs[i].startRow = i * rowsPerThread;
        threadArgs[i].endRow = (i + 1) * rowsPerThread;
        threadArgs[i].a=a;
        threadArgs[i].b=b;
        threadArgs[i].c=c;
        //printf("thread(%d)start\n",i);
        //printf("threadArgs[%d].n=%d\n",i,threadArgs[i].n);
        pthread_create(&threads[i], NULL, multiplyMatrices, &threadArgs[i]);
    }

    // 等待线程完成
    for (i = 0; i < NUM_THREADS; i++)
    {
        pthread_join(threads[i], NULL);
        //printf("thread(%d)finish\n",i);
    }
}
